<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.label" placeholder="请输入搜索信息" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          {{ scope.row.roleDesc }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="choiceMenu(row)">
            权限
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px"
               style="width: 400px; margin-left:50px;">
        <el-form-item :label="columnLabel.roleName">
          <el-input v-model="temp.roleName" type="text"/>
        </el-form-item>
        <el-form-item :label="columnLabel.roleDesc">
          <el-input v-model="temp.roleDesc" type="text"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-table ref="auth" :model="temp">
        <tree-table :data="data" :columns="columns" border/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {create, getPageRole, update} from "@/api/role";

  export default {
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'info',
          0: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        list: null,
        listLoading: true,
        downloadLoading: false,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          label: undefined,
          type: undefined,
          sort: 'id'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          auth: '权限',
          update: '编辑',
          create: '新增'
        },
        dialogPvVisible: false,
        temp: {
          roleName: '',
          roleDesc: '',
          isDelete: '',
        },
        columnLabel: {
          roleName: '角色名称',
          roleDesc: '描述',
        },
        data: [
          {
            name:'1',
            children: [
              {
                name: '1-1'
              },
              {
                name: '1-2'
              }
            ]
          },
          {
            name: `2`
          }
        ],
        columns: [
          {
            label: 'Checkbox',
            checkbox: true
          },
          {
            label: '',
            key: 'id',
            expand: true
          },
          {
            label: 'Event',
            key: 'event',
            width: 200,
            align: 'left'
          },
          {
            label: 'Scope',
            key: 'scope'
          }
        ]
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        getPageRole(this.listQuery).then(response => {
            this.total = response.data.total
            this.list = response.data.records
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1 * 1000)
          },
          error => {
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      statusFilter(status) {
        const statusMap = {
          1: '启用',
          0: '禁用'
        }
        return statusMap[status]
      },
      resetTemp() {
        this.temp = {
          roleName: '',
          roleDesc: '',
        }
      },
      handleCreate() {
        this.resetTemp(),
          this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm']
          .validate((valid) => {
            if (valid) {
              create(this.temp).then(() => {
                this.list.unshift(this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                }),
                  this.getList()
              })
            }
          })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm']
          .validate((valid) => {
            if (valid) {
              const tempData = Object.assign({}, this.temp)
              update(tempData).then(() => {
                const index = this.list.findIndex(v => v.id === this.temp.id)
                this.list.splice(index, 1, this.temp)
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                }),
                  this.getList()
              })
            }
          })
      },
      handleDelete(row) {
        const h = this.$createElement;
        this.$msgbox({
          title: '消息',
          message: h('p', null, [
            h('span', null, '确认要删除当前记录吗？ ')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(action => {
          const tempData = {'id': row.id, 'isDelete': 1}
          update(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            }),
              this.getList()
          })
        });
      },
      choiceMenu(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'auth'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['auth'].clearValidate()
        })
      }
    }
  }
</script>
